import React, { useState, useEffect, useRef } from "react";
import { Card, Button, Table, Modal, message } from "antd";
import { reqRoles, reqAddRole, reqAddRoleAuth, reqDeleteRole } from "../../api";
import AddRole from "./add-role";
import AddAuth from "./add-auth";

const Role = () => {
  const [isShowAdd, setIsShowAdd] = useState(false);
  const [isShowAuth, setIsShowAuth] = useState(false);
  const [roles, setRoles] = useState([]);
  const [currentRole, setCurrentRole] = useState(null);
  const addRoleFormRef = useRef(null);
  const addAuthRef = useRef(null);

  useEffect(() => {
    getRoles();
  }, []);

  const initColumn = () => {
    return [
      {
        title: "角色名称",
        dataIndex: "name",
      },
      {
        title: "创建时间",
        dataIndex: "create_time",
        render: (create_time) =>
          create_time && new Date(create_time).toLocaleString(),
      },
      {
        title: "授权时间",
        dataIndex: "auth_time",
        render: (auth_time) =>
          auth_time && new Date(auth_time).toLocaleString(),
      },
      {
        title: "授权人",
        dataIndex: "auth_name",
      },
      {
        title: "操作",
        render: (role) => (
          <span>
            <Button
              type="primary"
              onClick={() => showAuth(role)}
              style={{ marginRight: 10 }}
            >
              设置权限
            </Button>
            <Button type="default" onClick={() => deleteRole(role)}>
              删除
            </Button>
          </span>
        ),
      },
    ];
  };

  const showAuth = (role) => {
    setCurrentRole(role);
    setIsShowAuth(true);
  };

  const getRoles = async () => {
    const res = await reqRoles();
    if (res.status === 0) {
      setRoles(res.data);
    }
  };

  const addRole = async () => {
    try {
      const values = await addRoleFormRef.current.validateFields();
      setIsShowAdd(false);
      const res = await reqAddRole(values.roleName);
      if (res.status === 0) {
        message.success("添加角色成功");
        setRoles((prevRoles) => [...prevRoles, res.data]);
      } else {
        message.error(res.msg);
      }
    } catch (err) {
      console.log(err);
    }
  };

  const addAuth = async () => {
    setIsShowAuth(false);
    const role = { ...currentRole };
    role.menus = addAuthRef.current.getMenus();
    role.auth_time = Date.now();

    // 获取当前用户信息
    const user = JSON.parse(localStorage.getItem("user_key"));
    role.auth_name = user ? user.username : "Unknown";

    const res = await reqAddRoleAuth(role);
    if (res.status === 0) {
      message.success("角色授权成功");
      // 更新本地存储中的角色信息
      if (user.role._id === role._id) {
        user.role = role;
        localStorage.setItem("user_key", JSON.stringify(user));
      }
      getRoles();
    } else {
      message.error(res.msg);
    }
  };

  const deleteRole = async (role) => {
    Modal.confirm({
      title: `确认删除角色 ${role.name} 吗？`,
      okText: "确认",
      cancelText: "取消",
      onOk: async () => {
        const res = await reqDeleteRole(role._id);
        if (res.status === 0) {
          message.success("删除角色成功");
          getRoles();
        } else {
          message.error(res.msg);
        }
      },
    });
  };

  const columns = initColumn();
  const title = (
    <Button type="primary" onClick={() => setIsShowAdd(true)}>
      创建角色
    </Button>
  );

  return (
    <Card title={title}>
      <Table
        dataSource={roles}
        columns={columns}
        bordered
        rowKey="_id"
        pagination={{ defaultPageSize: 2 }}
      />
      <Modal
        title="添加角色"
        open={isShowAdd}
        onOk={addRole}
        onCancel={() => setIsShowAdd(false)}
        okText="确认"
        cancelText="取消"
      >
        <AddRole ref={addRoleFormRef} />
      </Modal>
      <Modal
        title="设置角色权限"
        open={isShowAuth}
        onOk={addAuth}
        onCancel={() => setIsShowAuth(false)}
        okText="确认"
        cancelText="取消"
      >
        <AddAuth ref={addAuthRef} role={currentRole} />
      </Modal>
    </Card>
  );
};

export default Role;
